#pragma once

#include <iostream>
#include <string>
#include <unistd.h>
#include <cstring>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include "Log.hpp"

using namespace std;

const int defaultbacklog = 10;

enum
{
    SOCK_CREATE_ERROR = 1,
    SOCK_BIND_ERROR,
    SOCK_LISTEN_ERROR
};

class Sock
{
public:
    Sock()
    :_sockfd(-1)
    {}

    ~Sock()
    {}

    void Create()
    {
        _sockfd = socket(AF_INET, SOCK_STREAM, 0);
        if(_sockfd < 0)
        {
            lg(Fatal, "error:%d, error string:%s", errno, strerror(errno));
            exit(SOCK_CREATE_ERROR);
        }  

        int opt = 1;
        setsockopt(_sockfd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));

        lg(Info, "sockfd create success...sockfd:%d", _sockfd);
    }

    void Bind(uint16_t port)
    {
        struct sockaddr_in local;
        socklen_t len = sizeof(local);
        
        local.sin_family = AF_INET;
        local.sin_port = htons(port);
        local.sin_addr.s_addr = INADDR_ANY;

        int m = bind(_sockfd, (struct sockaddr*)&local, len);
        if(m < 0)
        {
            lg(Fatal, "error:%d, error string:%s", errno, strerror(errno));
            exit(SOCK_BIND_ERROR);
        }

        lg(Info, "sockfd bind success...sockfd:%d", _sockfd);
    }

    void Listen()
    {
        int n = listen(_sockfd, defaultbacklog);
        if(n < 0)
        {
            lg(Fatal, "error:%d, error string:%s", errno, strerror(errno));
            exit(SOCK_LISTEN_ERROR);
        }

        lg(Info, "listen success...");
    }

    //判断客户端发送的信息, 这里需要返回newfd来进行通信, 只有服务器接收需要返回新的newfd
    int Accpet(string* clientip, uint16_t* clientport)
    {
        struct sockaddr_in peer;
        socklen_t len = sizeof(peer);

        int newfd = accept(_sockfd, (struct sockaddr*)&peer, &len);
        if(newfd < 0)
        {
            lg(Warning, "error:%d, error string:%s", errno, strerror(errno));
            return -1;
        }

        char ipstr[32];
        inet_ntop(AF_INET, &peer.sin_addr, ipstr, sizeof(ipstr));
        *clientip = ipstr;
        *clientport = ntohs(peer.sin_port);

        return newfd;
    }

    //客户端向服务器发送链接请求
    bool Connect(const string& serverip, const uint16_t& serverport)
    {
        struct sockaddr_in server;
        socklen_t len = sizeof(server);

        server.sin_family = AF_INET;
        server.sin_port = htons(serverport);
        inet_pton(AF_INET, serverip.c_str(), &(server.sin_addr));

        int m = connect(_sockfd, (struct sockaddr*)&server, len);
        if(m < 0)
        {
            std::cerr << "connect to " << serverip << ":" << serverport << " error" << std::endl;
            return false;
        }

        return true;
    }

    void Close()
    {
        close(_sockfd);
    }

    int Fd()
    {
        return _sockfd;
    }
private:
    int _sockfd;
};